<script>
import { commonRequest } from '@/api/commonlist';
// import { Message } from '@/utils/utils';
// import { getLocalStorage, setLocal } from '@/utils/utils';
// import { BUSINESSFIELDSKEY } from './CommonList.vue';

const MyTimerRange = () => import('common/formComponent/MyTimerRange.vue');
const MyInput = () => import('common/formComponent/MyInput.vue');
const MyPositon = () => import('common/formComponent/MyPositon.vue');
const MyScrollSelect = () => import('common/formComponent/MyScrollSelect.vue');
const MyRadioBox = () => import('common/formComponent/MyRadioBox.vue');
const MyCheckBox = () => import('common/formComponent/MyCheckBox.vue');
const MyRate = () => import('common/formComponent/MyRate.vue');
const MyTimePicker = () => import('common/formComponent/MyTimePicker.vue');
const MySelect = () => import('common/formComponent/MySelect.vue');
const MyFileChoose = () => import('common/formComponent/MyFileChoose.vue');

// const cacheRenderData = 'listDetailRenderData';
export default {

  props: {
    autoGetData: {
      type: Boolean,
      default: true
    },

    justLook: {
      type: Boolean,
      default: false
    },

    // 设置id (定制属性)
    lastIndex: {
      type: Number,
      default: -1
    }
  },

  data() {
    return {
      isSp: '', // 是否审批 1 需要选择时间
      tableIds: [],
      renderData: [],
      step: 0

    };
  },

  computed: {
    disabled() {
      return this.justLook;
    },

    formModuleState() {
      return this.$store.state.formModule;
    }
  },

  created() {
    // const query = this.$route.query;
    // const { tableIds: ids } = query;
    // const { autoGetData } = this;

    // if (!autoGetData) return;
    // if (ids) {
    //   const tableIds = ids.split(',');
    //   if (tableIds.length > 1) {
    //     this.tableIds = tableIds;
    //   } else {
    //     Message('tableId不完整');
    //   }
    // } else {
    //   Message('tableId没有拿到');
    // }

    // this.init();
  },

  methods: {
    // 下拉框点中
    selectFocus(item) {
      if (!item.myOption.length && !item.myLoading) {
        this.sendRequest(item);
      }
    },

    // 调用接口
    sendRequest(item) {
      const {
        focusUrlParams,
        focusUrl
      } = item;

      if (focusUrlParams && focusUrl) {
        const {
          data,
          method,
          header,
          type
        } = focusUrlParams;

        item.myOption = [];
        item.myLoading = true;
        // type:0, 入参字段类型【0-字符串（varchar），1-数字（number）】（调用function接口需要
        if (type === 1) {
          commonRequest(data, focusUrl, method, header).then(res => {
            const { success, data: resData } = res;
            item.myLoading = false;

            if (success) {
              item.myOption = resData;
              this.$forceUpdate();
            }
          });
        }
      }
    },

    selectChange(item, value, type) {
      // type 1 单选 2 多选

      if (type === 1) {
        // item.myValue = 'cqc';
      }
    },

    setItemValue(item, value) {
      item.myValue = value;
    },

    // changeStep(n) {
    //   this.step = n;
    // },

    // init() {
    //   const { tableIds, getData } = this;
    //   const { isSp } = this.$route.params;

    //   this.isSp = isSp;
    //   if (tableIds.length) {
    //     const data = getLocalStorage(cacheRenderData);
    //     if (data && data.length) {
    //       this.renderData = data;
    //     } else {
    //       getData();
    //     }
    //   }
    // },

    // getData() {
    //   return commonRequest(
    //     {
    //       tableId: this.tableIds[0]
    //     },
    //     '/dynamicHeader/findTableHeader',
    //     'get'
    //   ).then(res => {
    //     if (res.success) {
    //       res.data.forEach(item => {
    //         item.myValue = item.defaultValue || '';
    //       });

    //       this.setData(res.data.filter(item => item.status !== 1));
    //     }
    //   });
    // },
    setPersonalData(data) {
      const setDefaultKey = (item, key, defaultValue) => {
        if (!(key in item)) {
          item[key] = defaultValue;
        }
      };

      data.forEach(item => {
        setDefaultKey(item, 'myOption', []);
        setDefaultKey(item, 'myValue', '');
        setDefaultKey(item, 'myLoading', false);
      });

      return data;
    },

    setData(data) {
      data = this.setPersonalData(data);
      this.renderData = data;
    }

    // nextStep() {
    //   const { isApprove, listId } = this.$route.query;
    //   setLocal({
    //     [cacheRenderData]: this.renderData
    //   });
    //   this.$router.replace({
    //     path: `listDetailSp/${isApprove}/${listId}/${this.tableIds[0]}`
    //   });
    // }
  },

  render(h) {
    // const { myBottom } = this.$slots;
    // nextStep
    const { autoGetData, formModuleState, setItemValue } = this;
    const RenderComponentInstance = this.renderData.map((item, i) => {
      const {
        componentType,
        title,
        promptText: placeholder
      } = item;

      const commonProperty = {
        class: {
          renderItem: (i + 1) % 3 === 0,
          CommonInstance_instanceAddLast: this.lastIndex === i
          // renderItemDisabled: disabled
        },
        props: {
          title,
          placeholder,
          disabled: this.disabled,
          isShowIconArrow: true,
          loading: item.myLoading,
          value: item.myValue,
          icon: ''
        },
        on: {
          'update:value': v => setItemValue(item, v)
        }
      };

      const props = commonProperty.props;
      const on = commonProperty.on;

      // input 类型
      const inputInstance = (item, type) => {
        props.type = type;
        props.isShowIconArrow = false;
        if (type === 'textarea') {
          props.isShowIconArrow = false;
        }

        return h(MyInput, commonProperty);
      };

      // 地理位置
      const positionInstance = item => {
        return h(MyPositon, commonProperty);
      };

      // 选择年月日 | 时间区间
      const timerPickerInstance = (item, mode) => {
        props.mode = mode;
        return h(MyTimePicker, commonProperty);
      };

      // 单选
      const radioInstance = item => {
        const {
          selectViewOptions,
          columnSelectOptions
        } = item;
        props.dataList = columnSelectOptions || [];
        props.optionView = selectViewOptions && Object.keys(selectViewOptions).length && selectViewOptions || {
          label: 'label',
          value: 'value'
        };

        return h(MyRadioBox, commonProperty);
      };

      // 复选
      const checkboxInstance = item => {
        props.optionView = item.selectViewOptions || {
          label: 'label',
          value: 'value'
        };
        props.dataList = item.columnSelectOptions || [];
        return h(MyCheckBox, commonProperty);
      };

      const yearSelectInstance = (item, num) => {
        props.shownum = num;
        on.change = v => {
          item.myValue = v + '';
        };
        return h(MyScrollSelect, commonProperty);
      };

      const rateInstance = (item, count) => {
        props.count = count;
        props.value = item.myValue ? item.myValue * 1 : 0;
        return h(MyRate, commonProperty);
      };

      const timeSelectRangeInstance = (item, modeType) => {
        props.mode = 'range';
        props.modeType = modeType;
        return h(MyTimerRange, commonProperty);
      };

      // 选择
      const selectInstance = (item, options) => {
        const { selectViewOptions } = item;
        props.item = item;
        props.dataList = item.myOption;
        props.label = selectViewOptions.renderValue;
        props.idKey = selectViewOptions.renderMapKey;
        props.valueKey = selectViewOptions.renderKey;
        Object.assign(props, options);
        on.open = () => this.selectFocus(item);
        on.change = (value) => this.selectChange(item, value);
        return h(MySelect, commonProperty);
      };

      // 文件选择器
      const fileSelectInstance = (item, type) => {
        props.mode = type;
        props.loading = item.myLoading;

        return h(MyFileChoose, commonProperty);
      };

      const renderMap = {
        textArea: item => inputInstance(item, 'textarea'),
        input: item => inputInstance(item, 'input'),
        area: item => positionInstance(item),

        yearDateSelect: item => yearSelectInstance(item, 1),
        monthDateSelect: item => yearSelectInstance(item, 2),
        // dayDateSelect: item => yearSelectInstance(item, 3),
        dayDateSelect: item => timerPickerInstance(item, 'date'),
        dayDateSelectRange: item => timerPickerInstance(item, 'range'),
        // dayDateSelectRange: item => timeSelectRangeInstance(item, 'date'),
        yearDateSelectRange: item => timeSelectRangeInstance(item, 'year'),
        monthDateSelectRange: item => timeSelectRangeInstance(item, 'month'),

        radio: item => radioInstance(item),
        checkbox: item => checkboxInstance(item),

        batchSelect: item => selectInstance(item, {
          multiple: true
        }),
        [formModuleState.componentType.chooseFile]: item => fileSelectInstance(item, 'file'),
        [formModuleState.componentType.chooseImage]: item => fileSelectInstance(item, 'pic'),

        rate: item => rateInstance(item, 5),
        rate10: item => rateInstance(item, 10)
      };
      if (componentType in renderMap) {
        return renderMap[componentType](item);
      } else {
        return h('view', {
          class: 'renderItem'
        }, '未匹配到' + componentType + '类型的组件' + `[${item.title}]`);
      }
    });

    // const NextStepButton = myBottom || (autoGetData ? (
    //   <div
    //     class='mybtn normal fixedBottom'
    //     onClick={() => nextStep()}
    //   >
    //     下一步
    //   </div>
    // ) : '');

    return (
      <view class='commonView'>
        <view class={`commonView_container ${autoGetData && 'fullHeight'}`}>
          {
            this.step === 0
              ? RenderComponentInstance
              : ''
          }
        </view>
        {
          // NextStepButton
        }
      </view>
    );
  }
};
</script>

<style lang="scss" scoped>
.commonView {
  width: 100%;
  height: 100%;
  position: relative;
  // top: 10px;

  .commonView_container {
    // height: calc(100% - 45.6px);
    // overflow: auto;
    .renderItem {
      display: block;
      // margin: 10px 0;
      margin-bottom: 10px;
    }

    .renderItemDisabled {
      pointer-events: none;
    }

    &.fullHeight {
      height: 100%;
    }
  }

  .fixedBottom {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
  }
}
</style>
